/**
 * 统计管理器 - 管理番茄时钟的数据统计和分析
 * 负责统计数据的收集、计算、存储和可视化
 */
class StatisticsManager {
    constructor(settingsManager) {
        this.settingsManager = settingsManager;
        this.storageKey = 'pomodoroStatistics';
        
        // 统计数据结构
        this.defaultStats = {
            // 总体统计
            total: {
                pomodoros: 0,
                focusTime: 0, // 分钟
                sessions: 0,
                streakDays: 0,
                longestStreak: 0
            },
            // 每日统计 (格式: 'YYYY-MM-DD')
            daily: {},
            // 每周统计 (格式: 'YYYY-WW')
            weekly: {},
            // 每月统计 (格式: 'YYYY-MM')
            monthly: {},
            // 时段分布 (0-23小时)
            hourlyDistribution: {},
            // 最后更新时间
            lastUpdated: new Date().toISOString()
        };
        
        this.stats = this.loadStatistics();
        this.init();
    }
    
    /**
     * 初始化统计管理器
     */
    init() {
        console.log('StatisticsManager initialized');
        
        // 清理过期数据（保留90天）
        this.cleanupOldData();
    }
    
    /**
     * 加载统计数据
     */
    loadStatistics() {
        try {
            const stored = localStorage.getItem(this.storageKey);
            if (stored) {
                const parsedStats = JSON.parse(stored);
                return this.mergeStats(this.defaultStats, parsedStats);
            }
        } catch (error) {
            console.error('Failed to load statistics:', error);
        }
        
        return JSON.parse(JSON.stringify(this.defaultStats));
    }
    
    /**
     * 保存统计数据
     */
    saveStatistics() {
        try {
            this.stats.lastUpdated = new Date().toISOString();
            localStorage.setItem(this.storageKey, JSON.stringify(this.stats));
            return true;
        } catch (error) {
            console.error('Failed to save statistics:', error);
            return false;
        }
    }
    
    /**
     * 深度合并统计数据
     */
    mergeStats(defaultStats, userStats) {
        const merged = JSON.parse(JSON.stringify(defaultStats));
        
        function deepMerge(target, source) {
            for (const key in source) {
                if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
                    if (!target[key]) target[key] = {};
                    deepMerge(target[key], source[key]);
                } else {
                    target[key] = source[key];
                }
            }
        }
        
        deepMerge(merged, userStats);
        return merged;
    }
    
    /**
     * 记录完成的番茄
     */
    recordPomodoro(duration = 25) {
        const now = new Date();
        const today = this.formatDate(now);
        const thisWeek = this.formatWeek(now);
        const thisMonth = this.formatMonth(now);
        const hour = now.getHours();
        
        // 更新总体统计
        this.stats.total.pomodoros++;
        this.stats.total.focusTime += duration;
        
        // 更新每日统计
        if (!this.stats.daily[today]) {
            this.stats.daily[today] = {
                pomodoros: 0,
                focusTime: 0,
                sessions: 0,
                startTime: now.toISOString(),
                endTime: now.toISOString()
            };
        }
        this.stats.daily[today].pomodoros++;
        this.stats.daily[today].focusTime += duration;
        this.stats.daily[today].endTime = now.toISOString();
        
        // 更新每周统计
        if (!this.stats.weekly[thisWeek]) {
            this.stats.weekly[thisWeek] = { pomodoros: 0, focusTime: 0, days: 0 };
        }
        this.stats.weekly[thisWeek].pomodoros++;
        this.stats.weekly[thisWeek].focusTime += duration;
        
        // 更新每月统计
        if (!this.stats.monthly[thisMonth]) {
            this.stats.monthly[thisMonth] = { pomodoros: 0, focusTime: 0, days: 0 };
        }
        this.stats.monthly[thisMonth].pomodoros++;
        this.stats.monthly[thisMonth].focusTime += duration;
        
        // 更新时段分布
        if (!this.stats.hourlyDistribution[hour]) {
            this.stats.hourlyDistribution[hour] = 0;
        }
        this.stats.hourlyDistribution[hour]++;
        
        // 更新连续天数
        this.updateStreak();
        
        this.saveStatistics();
        console.log(`Pomodoro recorded: ${duration} minutes`);
    }
    
    /**
     * 记录会话开始
     */
    recordSessionStart() {
        const today = this.formatDate(new Date());
        
        if (!this.stats.daily[today]) {
            this.stats.daily[today] = {
                pomodoros: 0,
                focusTime: 0,
                sessions: 0,
                startTime: new Date().toISOString(),
                endTime: new Date().toISOString()
            };
        }
        
        this.stats.daily[today].sessions++;
        this.stats.total.sessions++;
        
        this.saveStatistics();
    }
    
    /**
     * 更新连续天数
     */
    updateStreak() {
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        
        const todayKey = this.formatDate(today);
        const yesterdayKey = this.formatDate(yesterday);
        
        // 如果今天有番茄记录
        if (this.stats.daily[todayKey] && this.stats.daily[todayKey].pomodoros > 0) {
            // 如果昨天也有记录，连续天数+1
            if (this.stats.daily[yesterdayKey] && this.stats.daily[yesterdayKey].pomodoros > 0) {
                this.stats.total.streakDays++;
            } else {
                // 重新开始计算连续天数
                this.stats.total.streakDays = 1;
            }
            
            // 更新最长连续天数
            if (this.stats.total.streakDays > this.stats.total.longestStreak) {
                this.stats.total.longestStreak = this.stats.total.streakDays;
            }
        }
    }
    
    /**
     * 获取今日统计
     */
    getTodayStats() {
        const today = this.formatDate(new Date());
        const todayStats = this.stats.daily[today] || {
            pomodoros: 0,
            focusTime: 0,
            sessions: 0
        };
        
        return {
            ...todayStats,
            averageFocusTime: todayStats.pomodoros > 0 ? 
                Math.round(todayStats.focusTime / todayStats.pomodoros) : 0
        };
    }
    
    /**
     * 获取本周统计
     */
    getWeekStats() {
        const thisWeek = this.formatWeek(new Date());
        const weekStats = this.stats.weekly[thisWeek] || {
            pomodoros: 0,
            focusTime: 0,
            days: 0
        };
        
        // 计算本周活跃天数
        const weekStart = this.getWeekStart(new Date());
        let activeDays = 0;
        
        for (let i = 0; i < 7; i++) {
            const day = new Date(weekStart);
            day.setDate(day.getDate() + i);
            const dayKey = this.formatDate(day);
            
            if (this.stats.daily[dayKey] && this.stats.daily[dayKey].pomodoros > 0) {
                activeDays++;
            }
        }
        
        return {
            ...weekStats,
            activeDays,
            averagePerDay: activeDays > 0 ? Math.round(weekStats.pomodoros / activeDays) : 0
        };
    }
    
    /**
     * 获取本月统计
     */
    getMonthStats() {
        const thisMonth = this.formatMonth(new Date());
        const monthStats = this.stats.monthly[thisMonth] || {
            pomodoros: 0,
            focusTime: 0,
            days: 0
        };
        
        // 计算本月活跃天数
        const now = new Date();
        const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
        let activeDays = 0;
        
        for (let day = new Date(monthStart); day <= now; day.setDate(day.getDate() + 1)) {
            const dayKey = this.formatDate(day);
            if (this.stats.daily[dayKey] && this.stats.daily[dayKey].pomodoros > 0) {
                activeDays++;
            }
        }
        
        return {
            ...monthStats,
            activeDays,
            averagePerDay: activeDays > 0 ? Math.round(monthStats.pomodoros / activeDays) : 0
        };
    }
    
    /**
     * 获取总体统计
     */
    getTotalStats() {
        const totalHours = Math.floor(this.stats.total.focusTime / 60);
        const totalMinutes = this.stats.total.focusTime % 60;
        
        return {
            ...this.stats.total,
            totalHours,
            totalMinutes,
            averageFocusTime: this.stats.total.pomodoros > 0 ? 
                Math.round(this.stats.total.focusTime / this.stats.total.pomodoros) : 0,
            averagePerDay: this.stats.total.streakDays > 0 ? 
                Math.round(this.stats.total.pomodoros / this.stats.total.streakDays) : 0
        };
    }
    
    /**
     * 获取最近N天的趋势数据
     */
    getTrendData(days = 7) {
        const data = [];
        const today = new Date();
        
        for (let i = days - 1; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(date.getDate() - i);
            const dateKey = this.formatDate(date);
            
            const dayStats = this.stats.daily[dateKey] || { pomodoros: 0, focusTime: 0 };
            
            data.push({
                date: dateKey,
                dateLabel: this.formatDateLabel(date),
                pomodoros: dayStats.pomodoros,
                focusTime: dayStats.focusTime
            });
        }
        
        return data;
    }
    
    /**
     * 获取时段分布数据
     */
    getHourlyDistribution() {
        const distribution = [];
        
        for (let hour = 0; hour < 24; hour++) {
            const count = this.stats.hourlyDistribution[hour] || 0;
            distribution.push({
                hour,
                label: `${hour.toString().padStart(2, '0')}:00`,
                count,
                percentage: this.stats.total.pomodoros > 0 ? 
                    Math.round((count / this.stats.total.pomodoros) * 100) : 0
            });
        }
        
        return distribution;
    }
    
    /**
     * 获取专注效率分析
     */
    getEfficiencyAnalysis() {
        const recentDays = this.getTrendData(30);
        const activeDays = recentDays.filter(day => day.pomodoros > 0);
        
        if (activeDays.length === 0) {
            return {
                averagePomodoros: 0,
                averageFocusTime: 0,
                mostProductiveHour: 0,
                consistency: 0,
                trend: 'stable'
            };
        }
        
        const totalPomodoros = activeDays.reduce((sum, day) => sum + day.pomodoros, 0);
        const totalFocusTime = activeDays.reduce((sum, day) => sum + day.focusTime, 0);
        
        // 找出最高效的时段
        const hourlyData = this.getHourlyDistribution();
        const mostProductiveHour = hourlyData.reduce((max, current) => 
            current.count > max.count ? current : max, hourlyData[0]).hour;
        
        // 计算一致性（活跃天数占比）
        const consistency = Math.round((activeDays.length / 30) * 100);
        
        // 计算趋势（最近7天vs前7天）
        const recent7 = recentDays.slice(-7).reduce((sum, day) => sum + day.pomodoros, 0);
        const previous7 = recentDays.slice(-14, -7).reduce((sum, day) => sum + day.pomodoros, 0);
        
        let trend = 'stable';
        if (recent7 > previous7 * 1.1) trend = 'improving';
        else if (recent7 < previous7 * 0.9) trend = 'declining';
        
        return {
            averagePomodoros: Math.round(totalPomodoros / activeDays.length),
            averageFocusTime: Math.round(totalFocusTime / activeDays.length),
            mostProductiveHour,
            consistency,
            trend
        };
    }
    
    /**
     * 导出统计数据
     */
    exportStatistics() {
        try {
            const exportData = {
                version: '2.0.0',
                exportDate: new Date().toISOString(),
                statistics: this.stats,
                summary: {
                    total: this.getTotalStats(),
                    today: this.getTodayStats(),
                    week: this.getWeekStats(),
                    month: this.getMonthStats(),
                    efficiency: this.getEfficiencyAnalysis()
                }
            };
            
            return exportData;
        } catch (error) {
            console.error('Failed to export statistics:', error);
            return null;
        }
    }
    
    /**
     * 重置统计数据
     */
    resetStatistics() {
        this.stats = JSON.parse(JSON.stringify(this.defaultStats));
        this.saveStatistics();
        console.log('Statistics reset');
    }
    
    /**
     * 清理过期数据
     */
    cleanupOldData() {
        try {
            const cutoffDate = new Date();
            cutoffDate.setDate(cutoffDate.getDate() - 90); // 保留90天
            
            // 清理每日数据
            for (const dateKey in this.stats.daily) {
                if (new Date(dateKey) < cutoffDate) {
                    delete this.stats.daily[dateKey];
                }
            }
            
            // 清理每周数据
            for (const weekKey in this.stats.weekly) {
                const [year, week] = weekKey.split('-W');
                const weekDate = this.getDateFromWeek(parseInt(year), parseInt(week));
                if (weekDate < cutoffDate) {
                    delete this.stats.weekly[weekKey];
                }
            }
            
            this.saveStatistics();
            console.log('Old statistics data cleaned up');
        } catch (error) {
            console.error('Failed to cleanup old data:', error);
        }
    }
    
    // 辅助方法
    formatDate(date) {
        return date.toISOString().split('T')[0];
    }
    
    formatWeek(date) {
        const year = date.getFullYear();
        const week = this.getWeekNumber(date);
        return `${year}-W${week.toString().padStart(2, '0')}`;
    }
    
    formatMonth(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        return `${year}-${month}`;
    }
    
    formatDateLabel(date) {
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        
        if (this.formatDate(date) === this.formatDate(today)) {
            return '今天';
        } else if (this.formatDate(date) === this.formatDate(yesterday)) {
            return '昨天';
        } else {
            return `${date.getMonth() + 1}/${date.getDate()}`;
        }
    }
    
    getWeekNumber(date) {
        const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
        const dayNum = d.getUTCDay() || 7;
        d.setUTCDate(d.getUTCDate() + 4 - dayNum);
        const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
        return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
    }
    
    getWeekStart(date) {
        const d = new Date(date);
        const day = d.getDay();
        const diff = d.getDate() - day + (day === 0 ? -6 : 1); // 周一为第一天
        return new Date(d.setDate(diff));
    }
    
    getDateFromWeek(year, week) {
        const simple = new Date(year, 0, 1 + (week - 1) * 7);
        const dow = simple.getDay();
        const ISOweekStart = simple;
        if (dow <= 4) {
            ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
        } else {
            ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
        }
        return ISOweekStart;
    }
}

// 导出统计管理器
if (typeof module !== 'undefined' && module.exports) {
    module.exports = StatisticsManager;
}